//
//  ThemeConfigModel.m
//  MZBasic
//
//  Created by Better on 2022/9/16.
//

//测试环境主题配置文件下载路径
static NSString *const ThemePlistUrlTest = @"https://iosupdate.bizgo.com/iOSTheme/theme.plist";
//正式环境主题配置文件下载路径
static NSString *const ThemePlistUrl = @"https://commonweb.bizgo.com/IOS/Theme/theme.plist";

#import "ThemeDownConfigModel.h"

@implementation ThemeModel

- (instancetype) initWithDic:(NSDictionary *)dic{
    if (self = [super init]) {
        self.version = dic[@"version"];
        self.name = dic[@"skinName"];
        self.nameCn = dic[@"nameCn"];
        self.nameEn = dic[@"nameEn"];
        self.startDate = dic[@"startDate"];
        self.endDate = dic[@"endDate"];
        self.url = dic[@"url"];
        self.path = dic[@"path"];
        self.imageUrl = dic[@"imageUrl"];
        self.HDImageUrl = dic[@"HDimageUrl"];
        self.isDefaultSkin = [dic[@"isDefaultSkin"] boolValue];
        self.isSelect = NO;
        self.isHide = [dic[@"isHide"] boolValue];
        self.apply = [dic[@"apply"] boolValue];
    }
    return self;
}
- (instancetype) initWithCoder:(NSCoder *)aDecoder {
    
    if (self = [super init]) {
        self.version = [aDecoder decodeObjectForKey:@"version"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.nameCn = [aDecoder decodeObjectForKey:@"nameCn"];
        self.startDate = [aDecoder decodeObjectForKey:@"startDate"];
        self.endDate = [aDecoder decodeObjectForKey:@"endDate"];
        self.url = [aDecoder decodeObjectForKey:@"url"];
        self.path = [aDecoder decodeObjectForKey:@"path"];
        self.imageUrl = [aDecoder decodeObjectForKey:@"imageUrl"];
        self.HDImageUrl = [aDecoder decodeObjectForKey:@"HDimageUrl"];
        self.isDefaultSkin = [[aDecoder decodeObjectForKey:@"isDefaultSkin"] boolValue];
        self.isHide = [[aDecoder decodeObjectForKey:@"isHide"] boolValue];
        self.apply = [[aDecoder decodeObjectForKey:@"apply"] boolValue];
    }
    return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.version forKey:@"version"];
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.nameCn forKey:@"nameCn"];
    [aCoder encodeObject:self.startDate forKey:@"startDate"];
    [aCoder encodeObject:self.endDate forKey:@"endDate"];
    [aCoder encodeObject:self.url forKey:@"url"];
    [aCoder encodeObject:self.path forKey:@"path"];
    [aCoder encodeObject:self.imageUrl forKey:@"imageUrl"];
    [aCoder encodeObject:self.imageUrl forKey:@"HDimageUrl"];
    [aCoder encodeObject:[NSNumber numberWithBool:self.isDefaultSkin] forKey:@"isDefaultSkin"];
    [aCoder encodeObject:[NSNumber numberWithBool:self.isHide] forKey:@"isHide"];
    [aCoder encodeObject:[NSNumber numberWithBool:self.apply] forKey:@"apply"];
}
@end

@implementation ThemeDownConfigModel

+ (NSFileManager *) fileManager{
    return [NSFileManager defaultManager];
}

+ (void) downLoadThemeConfigModelSuccess:(void(^)(BOOL isSuccess))success
                                 Failure:(void(^)(BOOL isFailure))failure {
//        NSURL *urlFile = [NSURL URLWithString:@"https://commonweb.bizgo.com/IOS/Theme/theme.plist"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *urlFile = [NSURL URLWithString:ThemePlistUrlTest];
            NSURLRequest *request = [NSURLRequest requestWithURL:urlFile];
            NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        sessionConfiguration.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
            NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
            NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                if (error) {
                    NSLog(@"error:%@",error.localizedDescription);
                    failure(YES);
        
                }
                if (data) {
                    
                    [self storeThemePlistWithdata:data];
                    success(YES);
                }
            }];
            [task resume];
    });
    
    
}
+ (BOOL) themeExistWithPath:(NSString *)path{
    NSString *filePath = [ThemeDownload upZipPath:path];
    BOOL isExists = [self.fileManager fileExistsAtPath:filePath];
    return isExists;
}
+ (NSString *) themePlistPath{
    NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString*path=[paths objectAtIndex:0];
    NSString *themePath = [NSString stringWithFormat:@"%@/theme.plist",path];
    return themePath;
}
+ (void) storeThemePlistWithdata:(NSData *)data{
    NSString *filePath = [self themePlistPath];
    BOOL isExists = [self.fileManager fileExistsAtPath:filePath];
    if(isExists){
        [self.fileManager removeItemAtPath:filePath error:nil];
    }
    //先判断是否存在 先删除
    [[self fileManager] createFileAtPath:filePath contents:data attributes:nil];
}
+ (NSDictionary *) readThemePlist{
    NSDictionary *dic;
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self themePlistPath]];
    if (isExists) {
        dic = [NSDictionary dictionaryWithContentsOfFile:[self themePlistPath]];
    }
    return dic;
}
+ (ThemeModel *) readThemeModelFromThemePlistWithName:(NSString *)name{
    ThemeModel *themeModel;
    NSDictionary *dic;
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self themePlistPath]];
    if (isExists) {
        dic = [NSDictionary dictionaryWithContentsOfFile:[self themePlistPath]];
        if (dic[@"version"] && [dic[@"version"] isKindOfClass:[NSArray class]]) {
            NSArray *array = dic[@"version"];
            for (NSDictionary *themeDic in array) {
                ThemeModel *themeDicModel = [[ThemeModel alloc]initWithDic:themeDic];
                if ([themeDicModel.name isEqualToString:name]) {
                    themeModel = themeDicModel;
                }
            }
        }
    }
    return themeModel;
}
/**
   get theme Version

  @return theme version
 */
+ (NSDictionary *) themeVersion{
    return [NSDictionary dictionary];
}
/**
   get theme Version

  @return Array all theme
 */
+ (NSArray <ThemeModel *>*) themeArray{
    NSMutableArray <ThemeModel *>*array = [NSMutableArray new];
    if ([self readThemePlist]) {
        NSDictionary *dic = [self readThemePlist];
        for (NSDictionary *themeDic in dic[@"version"]) {
            ThemeModel *themeModel = [[ThemeModel alloc]initWithDic:themeDic];
            if(!themeModel.isHide){
                [array addObject:themeModel];
            }
            
        }
    }
    return array;
}

/**
 compare Theme Version

 */
+ (BOOL *) manuallyNeedUpdateCompareWithLocalVersion:(ThemeModel *)themeModel{
    
    themeModel.version = themeModel.version?themeModel.version:@"0";
    //取当前主题的plist
    NSString *fullThemePath = [ThemeDownload upZipPath:themeModel.path];
    NSString *plistPath = [NSString stringWithFormat:@"%@/theme.plist",fullThemePath];
    BOOL isExists = [[self fileManager] fileExistsAtPath:plistPath];
    NSDictionary *dic;
    if (isExists) {
        dic = [NSDictionary dictionaryWithContentsOfFile:[self themePlistPath]];
    }else{
        return NO;
    }
    NSString *localVersion = @"0";
    if (dic) {
        if (dic[@"version"] && [dic[@"version"] isKindOfClass:[NSArray class]]) {
            NSArray *array = dic[@"version"];
            for (NSDictionary *themeDic in array) {
                ThemeModel *themeDicModel = [[ThemeModel alloc]initWithDic:themeDic];
                if ([themeDicModel.name isEqualToString:themeModel.name]) {
                    localVersion = themeDicModel.version;
                }
            }
        }
    }
    if ([themeModel.version integerValue] > [localVersion integerValue]) {
        return YES;
    }else{
        return NO;
    }
}
+ (void) autoNeedUpdateCompareWithLocalVersion{
    
    //本地目前使用主题--的版本号
    ThemeModel *localhemeModel = [self readCurrentTheme];
        BaseWeakSelf
        //下载的plist里面这个主题--的版本号
        [self downLoadThemeConfigModelSuccess:^(BOOL isSuccess) {
            if (isSuccess) {
                if ([self isShowFestivalTheme] && ![self festivalThemeAndOprationTheme]) {
                   
                    ThemeModel *serverThemeModel = [weakSelf readThemeModelFromThemePlistWithName:[self festivalTheme].name];
                    if (![self festivalThemeAndOprationTheme]){
                        //判断大小
                        if([serverThemeModel.version integerValue] > [localhemeModel.version integerValue]){
                            __strong typeof(weakSelf) strongSelf = weakSelf;
                            
                            BaseWeakSelf
                            [ThemeDownload downloadThemeFileWithUrl:serverThemeModel.url FilePath:serverThemeModel.path Success:^(BOOL isSuccess) {
                                [weakSelf themeSwitch:[self festivalTheme]];
//                                [ThemeDownConfigModel cacheCurrentTheme:[self festivalTheme]];
                            } Failure:^(BOOL isFailure) {
                                
                            }];
                        }else{
//                            __strong typeof(weakSelf) strongSelf = weakSelf;
//                            BaseWeakSelf
                            [ThemeDownload downloadThemeFileWithUrl:serverThemeModel.url FilePath:serverThemeModel.path Success:^(BOOL isSuccess) {
                                //需要判断是否手动切换过
                                [self themeSwitch:[self festivalTheme]];
//                                [ThemeDownConfigModel cacheCurrentTheme:[self festivalTheme]];
                            } Failure:^(BOOL isFailure) {

                            }];
                            
                        }
                    }else{

                        //如果切换成了默认主题则走默认主题
                        if(localhemeModel.isDefaultSkin){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                //切换默认主题
                                [[BZThemeManager sharedInstance] switchTheme:[[BZThemeDefaultExample alloc] init] Finished:^(BOOL isSuccess, NSString * _Nonnull strError) {
                                    [ThemeDownConfigModel deleteCurrentTheme];
                                }];
                            });
                        }else{
                            [ThemeDownload downloadThemeFileWithUrl:[self festivalTheme].url FilePath:[self festivalTheme].path Success:^(BOOL isSuccess) {
                                [weakSelf themeSwitch:[self readCurrentNormalTheme]];
                            } Failure:^(BOOL isFailure) {

                            }];
                        }
                        
                    }
                        
                    
                }else{
                    //删除festival主题 保证下次直接下载最新的主题
                    [ThemeDownConfigModel deleteFesticalTheme];
                    //删除手动标记--节日主题是如果有手动操作
                    if(![self isShowFestivalTheme]){
                        [ThemeDownConfigModel festivalThemeAndOprationThemeDelete];
                    }
                    
                    //本地存了主题版本才会去检测更新
                    if (localhemeModel && ![localhemeModel.name isEqualToString:@"default"]) {
                        //检测是否需要更新节日主题，如果是自动切换过去，如果过了时间自动切换回来之前的主题
                        ThemeModel *serverThemeModel = [weakSelf readThemeModelFromThemePlistWithName:localhemeModel.name];
                        //判断大小
                        if([serverThemeModel.version integerValue] > [localhemeModel.version integerValue]){
                            __strong typeof(weakSelf) strongSelf = weakSelf;
                            //如果服务端version大 那么需要下载更新 且重新切换当前主题
                            BaseWeakSelf
                            [ThemeDownload downloadThemeFileWithUrl:serverThemeModel.url FilePath:serverThemeModel.path Success:^(BOOL isSuccess) {
                                [weakSelf themeSwitch:serverThemeModel];
                                [ThemeDownConfigModel cacheCurrentTheme:serverThemeModel];
                            } Failure:^(BOOL isFailure) {
                                
                            }];
                        }else{
                            [weakSelf themeSwitch:serverThemeModel];
                            [ThemeDownConfigModel cacheCurrentTheme:serverThemeModel];
                        }
                    }else{
                        if ([localhemeModel.name isEqualToString:@"default"] || !localhemeModel) {
                            return;
                        }
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //切换默认主题
                            [[BZThemeManager sharedInstance] switchTheme:[[BZThemeDefaultExample alloc] init] Finished:^(BOOL isSuccess, NSString * _Nonnull strError) {
                                [ThemeDownConfigModel deleteCurrentTheme];
                            }];
                        });
                    }
                }
            }
        } Failure:^(BOOL isFailure) {
            
        }];
    
}
+ (void) themeSwitchFestival:(ThemeModel *)themeModel{
    dispatch_async(dispatch_get_main_queue(), ^{
        BZThemeDatasource *theme = [[BZThemeDatasource alloc]init];
        theme.themeModel = themeModel;
        [[BZThemeManager sharedInstance] switchTheme:theme Finished:^(BOOL isSuccess, NSString * _Nonnull strError) {
            
        }];
    });
}
+ (void) themeSwitch:(ThemeModel *)themeModel {
    //当前需要切换的主题 和 当前显示的主题为同一个 则不进行主题切换
    ThemeModel *localhemeModel = [self readCurrentTheme];
    if([localhemeModel.name isEqualToString:themeModel.name]){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        BZThemeDatasource *theme = [[BZThemeDatasource alloc]init];
        theme.themeModel = themeModel;
        [[BZThemeManager sharedInstance] switchTheme:theme Finished:^(BOOL isSuccess, NSString * _Nonnull strError) {
            
        }];
//        [ThemeDownConfigModel cacheCurrentTheme:themeModel];
    });
}
//是否需要展示节日装扮
+ (BOOL) isShowFestivalTheme{
    BOOL isShowFestival = NO;
    BOOL isValidDate = NO;
    ThemeModel *themeModel = [self festivalTheme];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //加上时间判断
    //取本地时间 判断是不是再节日的时间区间
    NSDate *Date = [NSDate date];
    NSString *dateStr = [dateFormatter stringFromDate:Date]; //默认会切换到系统当前时区

    NSDate *localDate = [dateFormatter dateFromString:dateStr];
    
    NSDate *startDate = [dateFormatter dateFromString:[self festivalTheme].startDate];
    NSDate *endDate = [dateFormatter dateFromString:[self festivalTheme].endDate];
//        NSDate *startDate = [dateFormatter dateFromString:@"2022-09-22 18:00:00"];
//        NSDate *endDate = [dateFormatter dateFromString:@"2022-09-22 18:55:09"];
    if([localDate compare:startDate]==NSOrderedDescending && [localDate compare:endDate]==NSOrderedAscending){
        isValidDate = YES;
    }
    if(themeModel.apply && isValidDate){
        return YES;
    }else{
        return NO;
    }
    return themeModel.apply;
}
+ (ThemeModel *) festivalTheme{
    ThemeModel *themeModel;
    NSArray <ThemeModel *>*array = [self themeArray];
    for (ThemeModel *themeModelIN in array) {
        if ([themeModelIN.name isEqualToString:@"festival"]) {
            themeModel = themeModelIN;
        }
    }
    return themeModel;
}

+ (NSString *) cacheThemePath:(NSString *)path{
    NSArray *rootPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *rootPath=[rootPaths objectAtIndex:0];
    NSString *themePath = [NSString stringWithFormat:@"%@/%@",rootPath,path];
    return themePath;
}
+ (BOOL) cacheCurrentTheme:(ThemeModel *)themeModel{
    
    if (themeModel) {
        BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheThemeModel"]];
        if (isExists) {
            [[self fileManager] removeItemAtPath:[self cacheThemePath:@"cacheThemeModel"] error:nil];
        }
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:themeModel];
        [[self fileManager] createFileAtPath:[self cacheThemePath:@"cacheThemeModel"] contents:data attributes:nil];
        return YES;
    }else{
        return NO;
    }
    
}
+ (ThemeModel *) readCurrentNormalTheme{
    ThemeModel *themeModel;
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheThemeModel"]];
    if (isExists) {
        NSData *data = [NSData dataWithContentsOfFile:[self cacheThemePath:@"cacheThemeModel"] options:nil error:nil];
        themeModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    return themeModel;
}
+ (ThemeModel *) readCurrentTheme{
    ThemeModel *themeModel;
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheThemeModel"]];
    if (isExists) {
        NSData *data = [NSData dataWithContentsOfFile:[self cacheThemePath:@"cacheThemeModel"] options:nil error:nil];
        themeModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    return themeModel;
}
+ (void) deleteCurrentTheme{
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheThemeModel"]];
    if (isExists) {
        [[self fileManager] removeItemAtPath:[self cacheThemePath:@"cacheThemeModel"] error:nil];
    }
        
}
+ (void) deleteFesticalTheme{
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheFestivalThemeModel"]];
    if (isExists) {
        [[self fileManager] removeItemAtPath:[self cacheThemePath:@"cacheFestivalThemeModel"] error:nil];
    }
}
+ (void) deleteNormalTheme{
    BOOL isExists = [[self fileManager] fileExistsAtPath:[self cacheThemePath:@"cacheThemeModel"]];
    if (isExists) {
        [[self fileManager] removeItemAtPath:[self cacheThemePath:@"cacheThemeModel"] error:nil];
    }
}

//节日手动设置
+ (void) festivalThemeAndOpration{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"festivalThemeAndOpration"];
}
//节日手动读取
+ (BOOL) festivalThemeAndOprationTheme{
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"festivalThemeAndOpration"];
}
//节日手动删除
+ (void) festivalThemeAndOprationThemeDelete{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"festivalThemeAndOpration"];
}
@end
